import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  serialport: {
    // 获取所有串口列表
    getPortList: () => ipcRenderer.invoke('serial-list'),
    // 获取所有串口列表回调
    onListPort: (callback) => ipcRenderer.on('serial-list', callback),
    // 打开串口
    openPort: (options) => ipcRenderer.invoke('serial-open', options),
    // 关闭串口
    closePort: (path) => ipcRenderer.invoke('serial-close', path),
    // 串口数据接收监听
    onSerialData: (callback) => ipcRenderer.on('serial-data', callback),
    // 串口错误监听
    onSerialError: (callback) => ipcRenderer.on('serial-error', callback),
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
